import { useAccessStore } from '@vben/stores';
import { buildUUID } from '@vben/utils';

import { sm3 } from 'sm-crypto-v2';

const baseUrl = import.meta.env.VITE_FILE_BASE_URL;
const clientId = import.meta.env.VITE_FILE_CLIENT_ID;
const appSecret = import.meta.env.VITE_FILE_APP_SECRET;
const appPublicKey = import.meta.env.VITE_FILE_PUBLIC_KEY;
export const getFileUrl = (fileId: any, isThumbnail: boolean) => {
  return getFileUrlCode(fileId, isThumbnail, null);
};
export const getFileUrlCode = (
  fileId: any,
  isThumbnail: boolean,
  fileCategoriesCode?: null | string,
) => {
  if (!fileId) {
    return '';
  }
  // 判断是否url
  if (fileId?.startsWith('http')) {
    return fileId;
  }
  // 判断是否base64图片
  if (fileId?.startsWith('data:image')) {
    return fileId;
  }
  // 判断是否绝对路径
  if (fileId?.startsWith('/')) {
    return fileId;
  }

  // 获取租户信息
  const accessStore = useAccessStore();
  const tenantId = accessStore.tenantId;
  const timestamp = Date.now();
  // 生成uuid
  const nonce = buildUUID();
  // 生成签名
  const allParams = {
    fileId,
    isThumbnail,
    'tenant-id': tenantId,
    timestamp,
    nonce,
    'client-id': clientId,
  } as any;
  if (fileCategoriesCode) {
    allParams.fileCategoriesCode = fileCategoriesCode;
  }
  const sortParams = sortAescParams(allParams);
  const dataStr = JSON.stringify(sortParams);
  const str = `${dataStr}&client-id=${clientId}&nonce=${nonce}&timestamp=${timestamp}${appPublicKey}`;
  // 标准化密钥（32字节）
  const keyBytes = normalizeKey(appSecret);
  const sign = sm3(str, { key: keyBytes, mode: 'hmac' });
  let retUrl = `${baseUrl}/infra/file/download/${fileId}?client-id=${clientId}&tenant-id=${tenantId}&fileId=${fileId}&sign=${sign}&isThumbnail=${isThumbnail}&nonce=${nonce}&timestamp=${timestamp}`;
  if (fileCategoriesCode) {
    retUrl += `&fileCategoriesCode=${fileCategoriesCode}`;
  }
  return retUrl;
};
const sortAescParams = (obj: any) => {
  const sortObj = {} as any;
  Object.keys(obj)
    .sort()
    .forEach((item) => {
      const itemOjb = obj[item];
      if (itemOjb !== null && itemOjb !== undefined) {
        sortObj[item] =
          typeof itemOjb === 'string' ? itemOjb : JSON.stringify(itemOjb);
      }
    });
  return sortObj;
};
// 密钥标准化函数
const normalizeKey = (key: string) => {
  const encoder = new TextEncoder();
  const keyBytes = typeof key === 'string' ? encoder.encode(key) : key;

  // SM3 要求密钥至少32字节
  if (keyBytes.length < 32) {
    const newKey = new Uint8Array(32);
    newKey.set(keyBytes);
    return newKey;
  }

  return keyBytes;
};
